package com.cameron.serviceedu.aop;

import com.cameron.annotation.AdminAuth;
import com.cameron.entity.BackendMemberDto;
import com.cameron.servicebase.config.exception.BusinessException;
import com.cameron.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

import static com.cameron.constant.RoleConstant.MEMBER_ADMIN;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/01/16/21:33
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public AuthInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1、如果不是映射到方法直接通过

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 2、检查是否有 AdminAuth 注解，没有则跳过认证
        if (!method.isAnnotationPresent(AdminAuth.class)) {
            return true;
        }
        //从redis中获取当前用户token
        String token = this.stringRedisTemplate.opsForValue().get("token");
        if (StringUtils.isEmpty(token)) {
            log.error("user token is null in AuthInterceptor -> 53");
            throw new BusinessException(40003, "无权限!");
        }
        //解析token为 java bean
        BackendMemberDto memberInfo = JwtUtils.getLoginMemberByToken(token);
        //若角色为空则不通过
        if (memberInfo == null || memberInfo.getRoles() == null) throw new BusinessException(40003, "无权限!");
        Integer roles = memberInfo.getRoles();
        //若不为管理员则拒绝访问
        if (roles != MEMBER_ADMIN) {
            throw new BusinessException(40003, "无权限!");
        }
        //通过
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
